<?php namespace App\Services\Oauth\Login;

use App\Services\Oauth\SC;
use App\Models\Oauth\Members as MembersModel;
use Validator, Lang, Request;

class Process
{
    /**
     * 判断是否已经登录
     *
     * @return boolean true|false
     */
    public function hasLogin()
    {
        $hasLogin = SC::getLoginSession();
        
        return $hasLogin ? true : false;
    }

    /**
     * 设置并返回加密密钥
     *
     * @return string 密钥
     */
    public function setPublicKey()
    {
        return SC::setPublicKey();
    }

    /**
     * 取得刚才设置的加密密钥
     * 
     * @return string 密钥
     */
    public function getPublicKey()
    {
        return SC::getPublicKey();
    }

    /**
     * 手动的验证csrftoken
     */
    private function checkCsrfToken()
    {
        $csrf = new \App\Services\CsrfValidate();
        $csrf->tokensMatch();
    }

    /**
     * 删除密钥
     * 
     * @return void
     */
    public function delPublicKey()
    {
        return SC::delPublicKey();
    }

    /**
     * 登录验证
     *
     * @param string $username 用户名
     * @param string $password 密码
     */
    public function check($username, $password)
    {
        $memberModel = new MembersModel();
        $userInfo = $memberModel->InfoByName($username);
        $sign = md5($userInfo['password'].$this->getPublicKey());
        $this->delPublicKey();

        if($sign != strtolower($password)) return false;

        //更新最后登陆状态
        $data['last_login_time'] = time();
        $data['last_login_ip'] = Request::ip();
        $memberModel->updateLastLoginInfo($userInfo->id, $data);

        //设置一些session待用
        SC::setLoginSession($userInfo);

        return $userInfo;
    }

    /**
     * 检测post过来的数据
     * 
     * @param string $username 用户名
     * @param string $password 密码
     */
    public function validate($username, $password)
    {
        $this->checkCsrfToken();
        $data = array( 'username' => $username, 'password' => $password );
        $rules = array( 'username' => 'required|min:1', 'password' => 'required|min:1' );
        $messages = array(
            'username.required' => Lang::get('login.please_input_username'),
            'username.min' => Lang::get('login.please_input_username'),
            'password.required' => Lang::get('login.please_input_password'),
            'password.min' => Lang::get('login.please_input_password')
        );
        $validator = Validator::make($data, $rules, $messages);
        if ($validator->fails()) {
            return $validator->messages()->first();
        }
        return false;
    }
}